<?php

namespace app\admin\controller;

use think\Cache;
use think\Session;
use think\Db;
use think\Image;
use think\Log;
use OSS\OssClient;
use OSS\Core\OssException;
use app\service\Token;

class Index extends Common
{
    
    public function index()
    {
        // echo '欢迎使用！';die;
        $icp = Db::name('config_system')->where('title', 'bottom')->cache(86400)->value('content');

        $admin = Session::get('admin', 'mmjtAdmin');
    
        $adminTypeData = Db::name('admin_type')->where('id', $admin['type'])->value('data');
        $adminTypeData = json_decode($adminTypeData, true);

        if ($admin['type'] == 1) {
            $adminTypeData = Db::name('category')->column('id');
        } else {
            $last_1 = Db::name('category')->where(['id'=>['in',$adminTypeData], 'tid'=>['<>', 0]])->column('tid');
            $last_2 = Db::name('category')->where(['id'=>['in',$last_1], 'tid'=>['<>', 0]])->column('tid');
            $adminTypeData = array_merge($adminTypeData, $last_1, $last_2);
        }

        $this->assign('adminTypeData', $adminTypeData);
        
        $this->assign('admin', $admin);
        $this->assign('icp', $icp);


        

        if (in_array($this->adminInfo['type'], [1,2,7])) {
            $kefu = Db::name('config_system')->where(['title' => 'id'])->value('content');
            $kefu = intval($kefu);

            $kefu = Db::name('user')->where(['id' => $kefu])->field('id,name,sex,age,last_login_time')->find();

            if ($kefu) {
                Session::set('kefu', $kefu, 'mmjtChats');
                $tokenData = array(
                    'userid' => $kefu['id'],
                    'time' => $kefu['last_login_time'],
                    'sex' => $kefu['sex']
                );
                $token = Token::createToken($tokenData);
                if($token['status']==200){
                    $kefu['token'] = $token['token'];
                }
                $this->assign('kefu', $kefu);
            }
        }

        //var_dump($adminTypeData);
        if($admin['type'] == 6){//超级代理
            return $this->fetch('indexinvite');
        }elseif($admin['type'] == 7){//法律顾问
            return $this->fetch('indexlawyer');
        }else{
            return $this->fetch();
        }
    }
    //超级代理登录首页
    public function main6()
    {
        return $this->fetch();
    }
    //法律顾问登录首页
    public function main7()
    {
        return $this->fetch();
    }
    public function main()
    {
        /*$jubao = Db::name('jubao')->order('id desc')->where('admin_id', null)->fetchSql(false)->limit(3)->select();
        $this->assign('jubao', $jubao);*/

        /*$ping = Db::name('dycomment t1')->field('t1.*')->join('user t2', 't2.id = t1.userid')->order('t1.comment_id desc')->fetchSql(false)->limit(5)->select();
        $this->assign('ping', $ping);*/

        $chat = Db::name('chat_warn t1')
            ->field('t1.*, t2.title, t2.title, t3.name nickname')
            ->join('chat_warn_word t2', 't1.word_id = t2.id')
            ->join('user t3', 't1.user_id = t3.id')
            ->where(['t2.is_hidden' => 0])
            ->order('t1.id desc')->limit(20)->select();
        $this->assign('chat', $chat);


        $userwarn = Db::name('user_warn_records t1')
            ->field('t1.*, t2.name nickname')
            ->join('user t2', 't1.user_id = t2.id')
            ->order('t1.id desc')->limit(4)->select();
        $this->assign('userwarn', $userwarn);

        $data = [];
        $data['platform_balance'] = Db::name('platform_balance')->where(['types' => 2])->cache(3600)->sum('money');

        $data['login_user'] = Db::name('user')->whereTime('last_login_datetime', 'd')->where('reg', 1)->count();
        $tongji = false;
        if($tongji){
            $ids = Db::name('user')->whereTime('register_datetime', 'd')->cache(3600)->column('id');
            if ($ids) {
                $data['cost_user'] = Db::name("order_common")->where(['user_id' => ["in", $ids], 'status' => 1, 'pays' => ['neq', 1]])->group('user_id')->cache(3600)->count();
                $data['new_liushui'] = Db::name("order_common")->where(['user_id' => ["in", $ids], 'status' => 1, 'pays' => ['neq', 1]])->cache(3600)->sum('money');

                $data['new_arpu'] = $data['new_liushui'] / count($ids);
                $data['new_arppu'] = $data['cost_user'] ? ($data['new_liushui'] / $data['cost_user']) : 0;
                $data['new_user'] = count($ids);
                $data['new_cost_rate'] = $data['new_user'] ? ($data['cost_user'] / $data['new_user']) : 0;
            } else {
                $data['login_user'] = 0;
                $data['cost_user'] = 0;
                $data['new_liushui'] = 0.00;
                $data['new_arpu'] = 0;
                $data['new_arppu'] = 0;
                $data['new_user'] = 0;
                $data['new_cost_rate'] = 0;
            }
        }
        $this->assign('tongji', $tongji);

        $data['auth_user'] = Db::name('user')->where(['reg'=>1, 'is_identity_authentication' => 2])->cache(3600)->count();
        $data['vip_user'] = Db::name('user')->where(['reg'=>1, 'noble_grade' => ['gt', 1]])->cache(3600)->count();
        $data['general_user'] = Db::name('user')->where(['reg'=>1, 'noble_grade' => ['elt', 1]])->cache(3600)->count();

        $data['users'] = Db::name('user')->where('reg', 1)->cache(3600)->count();

        $this->assign('data', $data);



        return $this->fetch();
    }

    //清空缓存
    public function cache_del()
    {
        Cache::clear();
        Log::write('手动清理缓存','info');
        // deldir(ROOT_PATH . 'apis' . DS . 'Interface' . DS . 'Runtime');
        return ['ret' => '清空成功'];
    }

    //上传图片
    public function upload()
    {
        if (request()->file('image')) {

            $switch = getenv('APP_OSS');

            if (!$switch) { //默认存本地服务器
                $file = request()->file('image');
                $image = Image::open($file);
                $filePath = $file->getRealPath();
                if (!$filePath) {
                    exit(json_encode(['err' => '非法操作']));
                }
                /*$ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);  //后缀
                $geshi = ['jpg', 'png', 'gif', 'jpeg', 'JPEG', 'JPG', 'GIF', 'PNG'];
                if (!in_array($ext, $geshi)) {
                    exit(json_encode(['err' => '图片格式不对，请换张图片吧']));
                }*/

                if ($file) {
                    $info = $file->move(ROOT_PATH . 'disk');

                    if ($info) {
                        $arr = explode(DIRECTORY_SEPARATOR, $info->getSaveName());

                        $thumb_ = explode('.', $info->getFilename());
                        $image->thumb(1000, 1000)->save(ROOT_PATH . 'disk' . DS . date('Ymd') . DS . $info->getFilename());
                        $image->thumb(600, 600)->save(ROOT_PATH . 'disk' . DS . date('Ymd') . DS . $thumb_[0] . '_thumb.' . $thumb_[1]);

                        $new = '/disk/' . $arr[0] . '/' . $arr[1];

                        return $new;
                    } else {
                        return json(['err' => $file->getError()]);
                    }
                }
            } else {
                $file = $_FILES['image'];

                if ($file) {
                    $image = \think\Image::open($file['tmp_name']);

                    $name = $file['name'];
                    $format = strrchr($name, '.');

                    $new = sha1(date('YmdHis', time()) . uniqid()) . $format;

                    $image->thumb(2000, 2000)->save(ROOT_PATH . 'disk' . DS . $new);

                    /*判断图片格式*/
                    $allow_type = ['.jpg', '.jpeg', '.gif', '.bmp', '.png'];
                    if (!in_array($format, $allow_type)) {
                        exit(json_encode(['code' => 400, 'msg' => '文件格式不在允许范围内哦']));
                    }

                    $dir = 'disk/uploads/image/' . date("Ymd") . '/';
                    $fileName = $dir . $new;
                    $localFile = str_replace('/index.php', '', $_SERVER['SCRIPT_FILENAME']) . '/disk/' . $new;

                    $accessKeyId = getenv('OSS_KEYID');
                    $accessKeySecret = getenv('OSS_KEYSECRET');
                    $endpoint = getenv('OSS_ENDPOINT');
                    $bucket = getenv('OSS_BUCKET');

                    try {
                        $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);

                        $result = $ossClient->uploadFile($bucket, $fileName, $localFile);

                        $thumb_ = explode('.', $new);
                        $thumb1 = $dir . $thumb_[0] . '_thumb.' . $thumb_[1];

                        $result = $ossClient->uploadFile($bucket, $thumb1, $localFile);

                    } catch (OssException $e) {
                        return json(['code' => 400, 'msg' => $e->getMessage()]);
                    }

                    unlink($localFile);

                    return '/' . $fileName;
                }
            }

        } else {
            return $this->fetch();
        }
    }

    //上传图片
    public function upload2()
    {
        if (request()->file('image')) {

            $switch = getenv('APP_OSS');

            if (!$switch) { //默认存本地服务器
                $file = request()->file('image');
                $image = Image::open($file);
                $filePath = $file->getRealPath();
                if (!$filePath) {
                    exit(json_encode(['err' => '非法操作']));
                }
                /*$ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);  //后缀
                $geshi = ['jpg', 'png', 'gif', 'jpeg', 'JPEG', 'JPG', 'GIF', 'PNG'];
                if (!in_array($ext, $geshi)) {
                    exit(json_encode(['err' => '图片格式不对，请换张图片吧']));
                }*/
                // 上传到本地
                // 移动到框架应用根目录/public/uploads/ 目录下
                if ($file) {
                    $info = $file->move(ROOT_PATH . 'disk');
                    // $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
                    if ($info) {
                        $arr = explode(DIRECTORY_SEPARATOR, $info->getSaveName());
                        $new = $arr[0] . '/' . $arr[1];

                        // 压缩图
                        $thumb_ = explode('.', $info->getFilename());
                        $image->thumb(800, 800)->save(ROOT_PATH . 'disk' . DS . date('Ymd') . DS . $info->getFilename());
                        $image->thumb(600, 600)->save(ROOT_PATH . 'disk' . DS . date('Ymd') . DS . $thumb_[0] . '_thumb.' . $thumb_[1]);

                        // 按照原图的比例生成一个最大为150*150的缩略图并保存为thumb.png
                        // $image->thumb(665, 665)->save($new);
                        return '/disk/' . $new;

                        // // 成功上传后 获取上传信息
                        // // 输出 jpg
                        // echo $info->getExtension();
                        // // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
                        // echo $info->getSaveName();
                        // // 输出 42a79759f284b767dfcb2a0197904287.jpg
                        // echo $info->getFilename();
                    } else {
                        // 上传失败获取错误信息
                        dump($file->getError());
                        // echo ;
                    }
                }
            } else {
                $file = $_FILES['image'];

                if ($file) {
                    $image = \think\Image::open($file['tmp_name']);

                    $name = $file['name'];
                    $format = strrchr($name, '.');

                    $new = sha1(date('YmdHis', time()) . uniqid()) . $format;

                    $image->thumb(800, 800)->save(ROOT_PATH . 'disk' . DS . $new);

                    /*判断图片格式*/
                    $allow_type = ['.jpg', '.jpeg', '.gif', '.bmp', '.png'];
                    if (!in_array($format, $allow_type)) {
                        exit(json_encode(['code' => 400, 'msg' => '文件格式不在允许范围内哦']));
                    }

                    $dir = 'disk/uploads/image/' . date("Ymd") . '/';
                    $fileName = $dir . $new;
                    $localFile = str_replace('/index.php', '', $_SERVER['SCRIPT_FILENAME']) . '/disk/' . $new;

                    $accessKeyId = getenv('OSS_KEYID');
                    $accessKeySecret = getenv('OSS_KEYSECRET');
                    $endpoint = getenv('OSS_ENDPOINT');
                    $bucket = getenv('OSS_BUCKET');

                    try {
                        $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);

                        $result = $ossClient->uploadFile($bucket, $fileName, $localFile);

                        $thumb_ = explode('.', $new);
                        $thumb1 = $dir . $thumb_[0] . '_thumb.' . $thumb_[1];

                        $result = $ossClient->uploadFile($bucket, $thumb1, $localFile);

                    } catch (OssException $e) {
                        return json(['code' => 400, 'msg' => $e->getMessage()]);
                    }

                    unlink($localFile);

                    return '/' . $fileName;
                }
            }

        } else {
            return $this->fetch();
        }
    }

    //图片集
    public function uploads()
    {
        if (request()->isPost()) {

            $switch = getenv('APP_OSS');

            if (!$switch) { //默认存本地服务器
                $file = request()->file('file');

                // $file = request()->file('images');

                // 要上传图片的本地路径
                $filePath = $file->getRealPath();
                if (!$filePath) {
                    exit(json_encode(['err' => '非法操作']));
                }
                /*$ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);  //后缀
                $geshi = ['jpg', 'mp4', 'png', 'gif', 'jpeg', 'JPEG', 'JPG', 'GIF', 'PNG'];
                if (!in_array($ext, $geshi)) {
                    exit(json_encode(['err' => '图片格式不对，请换张图片吧']));
                }*/

                if ($file) {
                    $info = $file->move(ROOT_PATH . 'disk');
                    $arr = explode(DIRECTORY_SEPARATOR, $info->getSaveName());
                    $new = 'disk/' . $arr[0] . '/' . $arr[1];

                    $image = Image::open(ROOT_PATH . $new);

                    $thumb_ = explode('.', $info->getFilename());
                    $image->thumb(800, 800)->save(ROOT_PATH . 'disk' . DS . date('Ymd') . DS . $info->getFilename());
                    $image->thumb(600, 600)->save(ROOT_PATH . 'disk' . DS . date('Ymd') . DS . $thumb_[0] . '_thumb.' . $thumb_[1]);

                    if ($info) {
                        $data = ['img' => '/' . $new, 'imgurl' => '/' . $new, 'text' => ''];
                        return json_encode($data);
                    } else {
                        dump($file->getError());
                    }
                }
            } else {
                $file = $_FILES['file'];

                if ($file) {
                    $image = Image::open($file['tmp_name']);

                    $name = $file['name'];
                    $format = strrchr($name, '.');

                    $new = sha1(date('YmdHis', time()) . uniqid()) . $format;

                    $image->thumb(800, 800)->save(ROOT_PATH . 'disk' . DS . $new);

                    $allow_type = ['.jpg', '.jpeg', '.gif', '.bmp', '.png'];
                    if (!in_array($format, $allow_type)) {
                        exit(json_encode(['code' => 400, 'msg' => '文件格式不在允许范围内哦']));
                    }

                    $dir = 'disk/uploads/image/' . date("Ymd") . '/';
                    $fileName = $dir . $new;
                    $localFile = str_replace('/index.php', '', $_SERVER['SCRIPT_FILENAME']) . '/disk/' . $new;

                    $accessKeyId = getenv('OSS_KEYID');
                    $accessKeySecret = getenv('OSS_KEYSECRET');
                    $endpoint = getenv('OSS_ENDPOINT');
                    $bucket = getenv('OSS_BUCKET');

                    try {
                        $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);

                        $ossClient->uploadFile($bucket, $fileName, $localFile);

                        if (1) {
                            $thumb_ = explode('.', $new);
                            $thumb1 = $dir . $thumb_[0] . '_thumb.' . $thumb_[1];

                            $ossClient->uploadFile($bucket, $thumb1, $localFile);
                        }
                    } catch (OssException $e) {
                        return json(['code' => 400, 'msg' => $e->getMessage()]);
                    }

                    unlink($localFile);

                    $data = ['img' => '/' . $fileName, 'imgurl' => '/' . $fileName, 'text' => ''];
                    return json_encode($data);
                }
            }
        }
    }

    //icon 图标
    public function fontawesome()
    {
        return $this->fetch();
    }

    //退出登陆
    public function out()
    {
        session(null, 'mmjtAdmin');
        $this->redirect(SITE_PATH . "/admin");
    }

    // 第三方登录配置
    public function sdk()
    {
        return $this->fetch();
    }

    // 通知模板配置
    public function temp()
    {
        $name = Db::name('member_config')->where('type', 'temp')->select();
        $this->assign('data', $name);
        if (request()->isAjax()) {

            $post = input('post.');
            if ($post) {
                foreach ($name as $k => $v) {
                    Db::name('member_config')->where('name', $v['name'])->setField('text', $post[$v['name']]);
                }
                $data = ['ret' => '保存成功'];
            } else {
                $data = ['err' => '提交参数错误'];
            }
        } else {
            $data = $this->fetch();
        }
        return $data;
    }

    public function videoUploads()
    {
        if (request()->file('video')) {

            $switch = getenv('APP_OSS');

            if (!$switch) {
                $file = request()->file('video');

                if ($file) {
                    $info = $file->validate([
                        'size' => 34556787,
                        'ext' => 'mp4,rm,rmvb,mov,mtv,wmv,avi,3gp,amv,dmv,flv'
                    ])->move(ROOT_PATH . 'disk' . DS . 'uploads' . DS . 'videos');

                    if ($info) {
                        $new = '/disk/uploads/videos/' . date('Ymd') . '/' . $info->getFilename();

                        return json(['ret' => $new]);
                    } else {
                        return json(['err' => $file->getError()]);
                    }
                } else {
                    return json(['err' => '请先上传文件']);
                }
            } else {
                $file = $_FILES['video'];

                if ($file) {
                    $name = $file['name'];
                    $format = strrchr($name, '.');

                    $info = request()->file("video")->validate([
                        'size' => 34556787,
                        'ext' => 'mp4,rm,rmvb,mov,mtv,wmv,avi,3gp,amv,dmv,flv'
                    ])->move(ROOT_PATH . 'disk' . DS . 'uploads' . DS . 'videos');

                    $new = 'disk/uploads/videos/' . $info->getSaveName();
                    $new = str_replace('\\', '/', $new);

                    $localFile = str_replace('/index.php', '', $_SERVER['SCRIPT_FILENAME']) . '/' . $new;

                    $accessKeyId = getenv('OSS_KEYID');
                    $accessKeySecret = getenv('OSS_KEYSECRET');
                    $endpoint = getenv('OSS_ENDPOINT');
                    $bucket = getenv('OSS_BUCKET');

                    try {
                        $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);

                        $result = $ossClient->uploadFile($bucket, $new, $localFile);

                        unset($info);
                        unlink($localFile);
                    } catch (OssException $e) {
                        return json(['err' => $e->getMessage()]);
                    }

                    return json(['ret' => '/' . $new]);
                }
            }
        } else {
            return $this->fetch('uploadvideo');
        }
    }

    public function audioUploads()
    {
        if (request()->file('audio')) {

            $switch = getenv('APP_OSS');

            if (!$switch) {
                $file = request()->file('audio');

                if ($file) {
                    $info = $file->validate([
                        'size' => 34556787,
                        'ext' => 'mp3,ogg,wav'
                    ])->move(ROOT_PATH . 'disk' . DS . 'uploads' . DS . 'audios');

                    if ($info) {
                        $new = '/disk/uploads/audios/' . date('Ymd') . '/' . $info->getFilename();

                        return json(['ret' => $new]);
                    } else {
                        return json(['err' => $file->getError()]);
                    }
                } else {
                    return json(['err' => '请先上传文件']);
                }
            } else {
                $file = $_FILES['audio'];

                if ($file) {
                    $name = $file['name'];
                    $format = strrchr($name, '.');

                    $info = request()->file("audio")->validate([
                        'size' => 34556787,
                        'ext' => 'mp3,ogg,wav'
                    ])->move(ROOT_PATH . 'disk' . DS . 'uploads' . DS . 'audios');

                    $new = 'disk/uploads/audios/' . $info->getSaveName();
                    $new = str_replace('\\', '/', $new);

                    $localFile = str_replace('/index.php', '', $_SERVER['SCRIPT_FILENAME']) . '/' . $new;

                    $accessKeyId = getenv('OSS_KEYID');
                    $accessKeySecret = getenv('OSS_KEYSECRET');
                    $endpoint = getenv('OSS_ENDPOINT');
                    $bucket = getenv('OSS_BUCKET');

                    try {
                        $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);

                        $result = $ossClient->uploadFile($bucket, $new, $localFile);

                        unset($info);
                        unlink($localFile);
                    } catch (OssException $e) {
                        return json(['err' => $e->getMessage()]);
                    }

                    return json(['ret' => '/' . $new]);
                }
            }
        } else {
            return $this->fetch('uploadaudio');
        }
    }

    //红包管理
    public function hongbao()
    {
        $where = [];

        $type = input('type');
        if ($type == 1) {
            $where['time'] = date('Y-m-d');
        }

        $search_name = input('param.name');
        $search_type = input('param.type');
        if ($search_name && $search_type) {
            $where[$search_type] = ['like', '%' . $search_name . '%'];
        }

        $data = Db::name('packetsum')->where($where)->order('id desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $this->assign('type', $type);
        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }

    //红包领取列表
    public function lingqulist()
    {
        $time = input('time');

        $data = Db::table('packet')
            ->alias('t1')
            ->field('t1.*,t2.name,t2.head_portrait')
            ->join('user t2', 't2.id = t1.user_id')
            ->where('time', $time)
            ->order('ltime desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }

    //添加红包
    public function hongbaoadd()
    {
        $id = input('id');

        if (request()->isAjax()) {

            $post = input('post.');

            if (!$post['money']) {
                return ['err' => '总金额不正确'];
            }

            if (!$post['top']) {
                return ['err' => '红包上限值不正确'];
            }

            if (!$post['bottom']) {
                return ['err' => '红包下限值不正确'];
            }


            if (!$id) {   //添加数据

                if (!$post['time']) {
                    return ['err' => '日期不正确'];
                }

                $res = Db::name('packetsum')->where('time', $post['time'])->find();
                if ($res) {
                    return ['err' => '当前日期以设置红包，无需重复添加'];
                }

                $post['shengyu'] = $post['money'];

                $db = Db::name('packetsum')->insert($post);
                if ($db) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else {  //修改数据
                $db = Db::name('packetsum')->where('id', $id)->update($post);
                if ($db !== false) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }
        } else {
            if ($id) {
                $name = Db::name('packetsum')->where('id', $id)->find();
                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }

    //删除红包
    public function hongdel()
    {
        if (request()->isAjax()) {

            $id = input('id');
            if ($id) {
                $db = Db::name('packetsum')->delete($id);
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    public function uploadvideo()
    {
        if (request()->file('video')) {
            $file = request()->file('video');

            $filePath = $file->getRealPath();
            if (!$filePath) {
                exit(json_encode(['err' => '非法操作']));
            }
            $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);  //后缀
            $geshi = ['mp4', 'wmv', '3gp', 'flv'];
            if (!in_array($ext, $geshi)) {
                exit(json_encode(['err' => '视频格式不对']));
            }
            // 上传到本地
            // 移动到框架应用根目录/public/uploads/ 目录下
            if ($file) {
                $info = $file->move(ROOT_PATH . 'disk');
                // $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
                if ($info) {
                    $arr = explode(DIRECTORY_SEPARATOR, $info->getSaveName());
                    return '/disk/' . $arr[0] . '/' . $arr[1];
                } else {
                    // 上传失败获取错误信息
                    dump($file->getError());
                }
            }
        } else {
            return $this->fetch();
        }
    }

    public function auditTip(){

        $list = db('admin_audit_audio')->select();
        // $adminId = $this->adminInfo['id'];
        $adminId = session_id();

        $data = [];
        foreach ($list as $key => $value) {
            $cachekey = 'auditTip:'.$value['table'].':'.$adminId;
            $last_id = cache($cachekey);
            $last_id = $last_id ?: 0;
            $ids = db($value['table'])
                ->where([$value['key']=>$value['value']])
                ->where([$value['pkey']=>['>', $last_id]])
                ->order($value['pkey'] . ' desc')
                ->column($value['pkey']);
            $len = sizeof($ids);
            if ($len) {
                cache($cachekey, $ids[0], 7200);
                $data[] = ['name'=>$value['name'], 'count'=>$len, 'menuid'=>$value['menuid'], 'audio'=>$value['audio'], 'id'=>$value['id']];
            }
        }

        return ['ret'=>$data];
    }
    
    public function auditTipSse()
    {
        header('Content-Type: text/event-stream');
        header('Cache-Control: no-cache');
        header('X-Accel-Buffering: no'); // Nginx 禁用缓冲
        set_time_limit(0);

        $adminId = session_id(); // 你也可以换成 $this->adminInfo['id']
        $lastCheckTime = time(); // 初始化上次检查时间

        while (true) {
            // 优化：通过缓存来减少数据库查询频率
            if (time() - $lastCheckTime < 5) {
                // 如果距离上次检查不到 5 秒，跳过
                sleep(1); 
                continue;
            }

            // 获取审核提示数据
            $list = Db::name('admin_audit_audio')->select();
            $data = [];

            foreach ($list as $value) {
                $cacheKey = 'auditTip:' . $value['table'] . ':' . $adminId;
                $last_id = Cache::get($cacheKey) ?: 0;

                $ids = Db::name($value['table'])
                    ->where($value['key'], $value['value'])
                    ->where($value['pkey'], '>', $last_id)
                    ->order($value['pkey'] . ' desc')
                    ->column($value['pkey']);

                if (count($ids) > 0) {
                    Cache::set($cacheKey, $ids[0], 7200);
                    $data[] = [
                        'name' => $value['name'],
                        'count' => count($ids),
                        'menuid' => $value['menuid'],
                        'audio' => $value['audio'],
                        'id' => $value['id']
                    ];
                }
            }

            // 每 5 秒推送一次数据
            echo "retry: 5000\n"; // 断线重连间隔（毫秒）
            echo "data: " . json_encode(['ret' => $data]) . "\n\n";
            ob_flush();
            flush();

            // 更新上次检查时间
            $lastCheckTime = time();

            // 使用短时间的睡眠间隔，以避免过高的 CPU 占用
            sleep(3); // 每秒检查一次
        }
    }
        //审核待办功能
    public function getdsh()
    {
        //动态待审核
        $dtdsh = Db::name('dymanic')
            ->alias('t1')
            ->field('t1.dy_id')
            ->join('dymanic_category t2', 't2.id = t1.category_id', 'LEFT')
            ->join('user t3', 't3.id = t1.userid', 'LEFT')
            ->where('t1.type', 0)
            ->where('t1.shenhe', 0)
            ->where('t1.class', 1)
            ->order('t1.dy_id', 'desc')
            ->count();
        //评论待审核
        $pldsh = Db::name('dycomment')
            ->alias('t1')
            ->field('t1.comment_id')
            ->join('user t2', 't2.id = t1.userid', 'INNER')
            ->where('t1.shenhe', 0)
            ->order('t1.comment_id', 'desc')
            ->count();
        //相册待审核
        $xcdsh = Db::name('user_img')
            ->alias('t1')
            ->field('t1.id')
            ->join('user t2', 't2.id = t1.user_id', 'INNER')
            ->where('t1.status', 0)
            ->order('t1.time', 'desc')
            ->count();
        //信息待审核
        $xxdsh = Db::name('user_certification')
            ->alias('t1')
            ->field('t1.id')
            ->join('user t2', 't2.id = t1.user_id', 'INNER')
            ->where('t1.status', 0)
            ->order('t1.create_time', 'desc')
            ->count();
        //招呼语待审核
        $zhdsh= Db::name('privatechat_greet')
            ->alias('t1')
            ->field('t1.id')
            ->where('t1.status', 0)
            ->order('t1.id', 'desc')
            ->count();
        //资料待审核
        $zldsh= Db::name('user_material_verify')
            ->alias('t1')
            ->field('t1.id')
            ->join('user t2', 't2.id = t1.user_id', 'INNER')
            ->where('t1.status', 0)
            ->order('t1.create_time', 'desc')
            ->count();
        //认证待审核
        $rzdsh= Db::name('user_attestation')
            ->alias('t1')
            ->field('t1.id')
            ->join('user t2', 't2.id = t1.user_id', 'INNER')
            ->where('t1.status', 0)
            ->order('t1.create_time', 'desc')
            ->count();
        //常用语待审核
        $cyydsh= Db::name('privatechat_default')
            ->alias('t1')
            ->field('t1.id')
            // ->where('user_id', '<>', 6382)
            ->where('t1.shenhe_state', 0)
            ->order('t1.id', 'desc')
            ->count();
        //绑定申请待审核
        $bdsqdsh= Db::name('user_invite_apply')
            ->alias('t1')
            ->field('t1.id')
            ->where('t1.state', 0)
            ->order('t1.id', 'desc')
            ->count();
        //致命预警数量
        $fatal_warn = Db::name('chat_warn')->where(['is_banned'=>0,'word_id'=>['in',[46,47,48,49,50]]])->group('user_id')->count();
        $navdsh=$dtdsh.','.$pldsh.','.$xcdsh.','.$xxdsh.','.$zhdsh.','.$zldsh.','.$rzdsh.','.$cyydsh.','.$bdsqdsh.','.$fatal_warn;
        echo $navdsh;
    }
}
